#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    udpSocket = new QUdpSocket(this);
    udpSocketSender = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::Any, ui->lePort->text().toInt());
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(on_udpSocket_recvive()));

    connect(ui->teRecvText, SIGNAL(textChanged()), this, SLOT(on_teRecvText_scroll()));
    connect(ui->teSendText, SIGNAL(textChanged()), this, SLOT(on_teSendText_scroll()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_udpSocket_recvive()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QNetworkDatagram datagram = udpSocket->receiveDatagram();
        ui->teRecvText->insertPlainText(datagram.data());
    }
}

void MainWindow::on_pbSend_clicked()
{
    QByteArray data(ui->teSendText->toPlainText().toStdString().c_str(), ui->teSendText->toPlainText().toStdString().size());
    quint16 port = ui->lePort->text().toInt();

    if(ui->rbBroadcast->isChecked())
    {
        udpSocketSender->writeDatagram(data, QHostAddress::Broadcast, port);
    }else if(ui->rbNormal->isChecked())
    {
        QString ip(ui->leIPAddr->text());
        QHostAddress hostaddr(ip);
        udpSocketSender->writeDatagram(data, hostaddr, port);
    }
}


void MainWindow::on_teSendText_scroll()
{
    ui->teSendText->moveCursor(QTextCursor::End);
}

void MainWindow::on_teRecvText_scroll()
{
    ui->teRecvText->moveCursor(QTextCursor::End);
}

void MainWindow::on_pbClearSend_clicked()
{
    ui->teSendText->clear();
}

void MainWindow::on_pbClearRecv_clicked()
{
    ui->teRecvText->clear();
}
